import useTagsViewStore from '@/store/modules/tagsView'
import router from '@/router'
import { type RouteLocationNormalizedLoaded, type RouteLocationRaw } from 'vue-router'

export default {
  // 刷新当前tab页签
  async refreshPage(obj: { name?: string; path: string; query: any }) {
    const { path, query, matched } = router.currentRoute.value
    if (obj === undefined) {
      matched.forEach((m) => {
        if (m.components?.default?.name) {
          if (!['Layout', 'ParentView'].includes(m.components.default.name)) {
            obj = { name: m.components.default.name, path, query }
          }
        }
      })
    }
    await useTagsViewStore()
      .delCachedView(obj)
      .then(() => {
        const { path, query } = obj
        void router.replace({
          path: `/redirect${path}`,
          query,
        })
      })
  },
  // 关闭当前tab页签，打开新页签
  async closeOpenPage(obj: RouteLocationRaw | undefined) {
    void useTagsViewStore().delView(router.currentRoute.value)
    if (obj !== undefined) {
      return await router.push(obj)
    }
  },
  // 关闭指定tab页签
  async closePage(obj: RouteLocationNormalizedLoaded | undefined) {
    if (obj === undefined) {
      return await useTagsViewStore()
        .delView(router.currentRoute.value)
        .then(async ({ lastPath }: any) => {
          return await router.push(lastPath || '/index')
        })
    }
    return await useTagsViewStore().delView(obj)
  },
  // 关闭所有tab页签
  async closeAllPage() {
    return await useTagsViewStore().delAllViews()
  },
  // 关闭左侧tab页签
  async closeLeftPage(obj: any) {
    return await useTagsViewStore().delLeftTags(obj || router.currentRoute.value)
  },
  // 关闭右侧tab页签
  async closeRightPage(obj: any) {
    return await useTagsViewStore().delRightTags(obj || router.currentRoute.value)
  },
  // 关闭其他tab页签
  async closeOtherPage(obj: any) {
    return await useTagsViewStore().delOthersViews(obj || router.currentRoute.value)
  },
  // 打开tab页签
  async openPage(url: RouteLocationRaw) {
    return await router.push(url)
  },
  // 修改tab页签
  updatePage(obj: RouteLocationNormalizedLoaded) {
    useTagsViewStore().updateVisitedView(obj)
  },
}
